package cn.lyf.myblog.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.lyf.myblog.dataFlow.Flow;
import cn.lyf.myblog.mybatis.mappers.*;

import static cn.lyf.myblog.controller.api.JsonUtils.*;

import java.util.*;
import java.util.stream.*;

@Service
public class LikeService {

    final Flow<Map<String, Object>> flow = new Flow<>();

    @Autowired
    LikesMapper likesMapper;
    @Autowired
    UserInfo2Mapper userInfo2Mapper;
    @Autowired
    BlogMapper blogMapper;

    // userId
    // blogId
    public int ins(JsonNode json) throws Exception {
        Integer uid = getInteger(json, "/userId");
        Integer bid = getInteger(json, "/blogId");
        return likesMapper.insertLike(uid, bid);
    }

    public int del(JsonNode json) throws Exception {
        Integer uid = getInteger(json, "/userId");
        Integer bid = getInteger(json, "/blogId");
        return likesMapper.deleteLike(uid, bid);
    }

    public JsonNode readLike(JsonNode json) throws Exception {
        List<Integer> l = mapper.readValue(json.get("messageId").toString(), new TypeReference<List<Integer>>() {
        });
        likesMapper.readLikes(l,getInteger(json,"/uid"));
        ObjectNode res = mapper.createObjectNode();
        res.put("success", true);
        res.put("code", 200);
        res.put("message", "点赞阅读成功");
        return res;
    }
    public JsonNode hideLike(JsonNode json) throws Exception {
        List<Integer> l = mapper.readValue(json.get("messageId").toString(), new TypeReference<List<Integer>>() {
        });
        likesMapper.hideLikes(l,getInteger(json,"/uid"));
        ObjectNode res = mapper.createObjectNode();
        res.put("success", true);
        res.put("code", 200);
        res.put("message", "点赞删除成功");
        return res;
    }

    public JsonNode getLikesList(JsonNode json) {
        List<Map<String, Object>> list = likesMapper.selectByUid(getInteger(json, "/uid"));
        list = list.stream().map(this::getlikesInfo).collect(Collectors.toList());
        return mapper.valueToTree(list);
    }

    Map<String, Object> getlikesInfo(Map<String, Object> map) {
        Integer uid = ((Long) map.get("uid")).intValue();
        Integer bid = ((Long) map.get("bid")).intValue();
        map.remove("uid");
        map.remove("bid");
        map.put("blog", blogMapper.selectById(bid));
        map.put("user", userInfo2Mapper.selectUserInfo2ById(uid));
        return map;
    }

}
